import { Component, OnInit, ViewChild, OnDestroy, AfterContentInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { TitleService, SettingsService } from '@delon/theme';
import { Constant, ServiceResult } from '@core/constant';
import { ProductService } from '../../../../service/prod/product.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import { OrderService } from '../../../../service/order/order.service';
import { SimpleTableColumn, SimpleTableComponent } from '@delon/abc';
import { format } from 'date-fns';

@Component({
  selector: 'client-order-view-edit',
  templateUrl: './order-view.component.html',
  styleUrls: ['./order-view.component.less']
})
export class ClientOrderViewComponent implements OnInit, OnDestroy {
    syncing = false;
    isManager = false;
    loading = false;
    sub: any;
    id;
    order: {[proname: string]: any} = {};
    currentStep = -1;
    imgSuffix = '';
    defaultUrl = './assets/tmp/img/dummy.png';  
    // 显示图片
    previewVisible = false;
    // 大图地址
    previewImage = '';
    columns: SimpleTableColumn[] = [
        { title: '', index: 'img', render: 'img', type: "img", width: "50px" },
        { title: 'SKU', index: 'productCd', render: 'sku' },                
        { title: '数量', index: 'qty', i18n: 'qty', type: 'number' }, 
        { title: '已确认数量', index: 'confirmQty', i18n: 'confirmQty', type: 'number', },
        { title: '已发数量', index: 'sendQty', i18n: 'sendQty', type: 'number'  },                 
        { title: '价格', render: 'price', i18n: 'price', type: 'currency' },
        { title: '总价', render: 'totalPrice', i18n: 'totalPrice', type: 'currency' } 
    ];

    visible = false;
    childrenVisible = false;
    currency = null;

    pzDate = null;
    jhDate = null;
    remark = null;
    totalConfirmQty = 0;
    @ViewChild('st') st: SimpleTableComponent;
    buildColumn() {
        if (this.order.level === 'FIRST') {
            this.columns = [
                { title: '', index: 'img', render: 'img', type: "img", width: "50px" },
                { title: 'SKU', index: 'productCd', render: 'sku' }, 
                { title: '库存', index: 'stock', i18n: 'stock', type: 'number'},
                { title: '数量', index: 'qty', i18n: 'qty', type: 'number' }, 
                { title: '已确认数量', index: 'confirmQty', i18n: 'confirmQty', type: 'number' },
                { title: '已发数量', index: 'sendQty', i18n: 'sendQty', type: 'number'  },                 
                { title: '价格', render: 'price', i18n: 'price', type: 'currency', index: 'price' },
                { title: '总价', render: 'totalPrice', i18n: 'totalPrice', type: 'currency', index: 'totalPrice' } 
            ]
        } else {
            this.columns = [
                { title: '', index: 'img', render: 'img', type: "img", width: "50px" },
                { title: 'SKU', index: 'productCd', render: 'sku' },                
                { title: '数量', index: 'qty', i18n: 'qty', type: 'number' },                 
                { title: '已发数量', index: 'sendQty', i18n: 'sendQty', type: 'number'  },                 
                { title: '价格', render: 'price', i18n: 'price', type: 'currency', index: 'price' },
                { title: '总价', render: 'totalPrice', i18n: 'totalPrice', type: 'currency', index: 'totalPrice' } 
            ]
        }
    }

    constructor(
        private msg: NzMessageService,
        private modalService: NzModalService,
        private productService: ProductService,
        private emit: EmitterService,
        private notification: NzNotificationService,
        private route: ActivatedRoute,
        private titleService: TitleService,
        private cnt: Constant,
        private router: Router,
        private comm: CommService,
        private orderServ: OrderService,
        private settings: SettingsService
    ) {
        this.isManager = this.settings.user.isManager;
    }

    confirmQty() {
        this.totalConfirmQty = 0;
        if (this.order && this.order.details) {
            for (let i = 0; i < this.order.details.length; i++) {
                this.totalConfirmQty += this.order.details[i].confirmQty;
            }
        }
        return this.totalConfirmQty;
    }

    // 显示reusetab
    ngOnDestroy() {    
        this.emit.sendMessage("SHOW_REUSE_TAB");
    }

    ngOnInit() {      
      this.currency = this.settings.user.currency;
      this.imgSuffix = this.comm.getGoodsUrl();
      // 获取参数
      this.sub = this.route.params.subscribe(params => {
        this.id = params["id"];  
        this.info();
      });
      // 隐藏reusetab
      setTimeout(() => {
          this.emit.sendMessage("HIDE_REUSE_TAB");
      }, 100);    
      this.titleService.setTitle("Order detail");          
    }

    back() {
        this.router.navigate(['/order/clientorder']);
    }

    info() {
        this.loading = true;
        this.orderServ.detail(this.id).pipe(catchError(err => {
            return of(err);
        })).subscribe(data => {
            this.loading = false;
            if (data.status === 200) {
                this.order = data.data; 
                this.setOrderStep();
                this.buildColumn();                               
            } else {
                this.msg.error(data.message);
            }
        })
    }

    setOrderStep() {
        if (this.order.status === 'NOCHECK') {
            this.currentStep = 0;
        } else if (this.order.status === 'CHECKED') {
            this.currentStep = 1;
        } else if (this.order.status === 'CANCEL') {
            this.currentStep = -1;
        }
       
        if (this.order.sendStatus === 'SENDING') {
            this.currentStep = 2;
        }
        if (this.order.sendStatus === 'SENDED') {
            this.currentStep = 3;
        }
    }

    showImage(src) {
        this.previewImage = src;
        this.previewVisible = true;
    }

    sure() {                    
        // 如果非管理账号, 直接提示并调用后台; 管理账号则弹窗输入一些参数
        if (this.settings.user.isManager) {
            this.open();
        } else {
            this.modalService.confirm({
                nzTitle     : 'Are you sure?',
                nzContent   : '<b style="color: red;">The order will be confirm</b>',
                nzOkText    : 'Yes',            
                nzOnOk      : () => {
                    this.loading = true;
                    this.orderServ.sureOrder(this.id).pipe(catchError(err => {
                        return of(err)
                    })).subscribe(data => {
                        this.loading = false;
                        if (data.status === 200) {
                            this.msg.success('Successful');
                            this.info();
                            this.emit.sendMessage("RELOAD_ORDERS_LIST");
                        } else {                            
                            this.modalService.error({
                                nzTitle: 'Failed',
                                nzContent: data.message
                            });
                        }
                    })
                },
                nzCancelText: 'No',
                nzOnCancel  : () => {}
            });
        }
    }

    cancelOrder() {
        this.modalService.confirm({
            nzTitle     : 'Are you sure?',
            nzContent   : '<b style="color: red;">The order will be cancel</b>',
            nzOkText    : 'Yes', 
            nzOkType    : 'danger',           
            nzOnOk      : () => {
                this.loading = true;
                this.orderServ.cancelOrder(this.id).pipe(catchError(err => {
                    return of(err)
                })).subscribe(data => {
                    this.loading = false;
                    if (data.status === 200) {
                        this.msg.success('Successful');
                        this.info();
                        this.emit.sendMessage("RELOAD_ORDERS_LIST");
                    } else {
                        this.modalService.error({
                            nzTitle: 'Failed',
                            nzContent: data.message
                        });
                    }
                })
            },
            nzCancelText: 'No',
            nzOnCancel  : () => {}
        });
    }


    open(): void {
        this.pzDate = null;
        this.jhDate = null;
        this.remark = null;
        this.visible = true;
    }

    close(): void {
        this.visible = false;
    }

    submit(): void {
        if (!this.pzDate) {
            this.msg.warning('凭证日期不能空');
            return;
        }
        if (!this.jhDate) {
            this.msg.warning('交货日期不能空');
            return;
        }     
        if (!this.remark) {
            this.msg.warning('备注不能空');
            return;
        }
        this.close();
        this.loading = true;
        this.orderServ.sureOrder(this.id, 
                format(this.pzDate, "YYYYMMDD"), 
                format(this.jhDate, "YYYYMMDD"), this.remark).pipe(catchError(err => {
            return of(err)
        })).subscribe(data => {
            this.loading = false;
            if (data.status === 200) {
                this.msg.success('Successful');
                this.info();
                this.emit.sendMessage("RELOAD_ORDERS_LIST");
            } else {                
                this.modalService.error({
                    nzTitle: 'Failed',
                    nzContent: data.message
                });
            }
        })
    }

    openChildren(): void {
        this.childrenVisible = true;
    }

    closeChildren(): void {
        this.childrenVisible = false;
    }

    exportDetail() {
        let exportData = this.order.details;
        for (let i = 0; i < exportData.length; i++) {
            exportData[i].price = exportData[i].price;
            exportData[i].totalPrice = exportData[i].price * exportData[i].qty;
        }
        this.st.export(exportData);
    }

    doSycnStock() {
        this.syncing = true;
        this.orderServ.dosyncordersku(this.id).pipe(catchError(err => {
            return of(err)
        })).subscribe(data => {
            if (data.status === 200) {
                this.syncing = true;
                this.refreshStatus();
            } else {
                this.syncing = false;
                this.msg.error(data.message);
            }
        })
    }
    syncInter = null;
    refreshStatus() {
        this.syncInter = setInterval(() => {
            this.orderServ.getsyncorderskustock(this.id).pipe(catchError(err => {
                return of(err)
            })).subscribe(data => {
                if (data.status === 200) {
                    // 执行结束
                    if (data.data.status === 0) {
                        this.syncing = false;
                        clearInterval(this.syncInter);
                        this.info();
                    } 
                } else {
                    this.syncing = false;
                    clearInterval(this.syncInter);
                }
            })
        }, 1000);
    }
}